# Untitled - By: lenovo - Fri Sep 6 2024


import sensor
import image
import time
import machine
from pyb import UART
from image import SEARCH_EX, SEARCH_DS

sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
# 取消自动曝光，设置曝光时间为10ms
sensor.set_auto_exposure(False, exposure_us=10000)
# 设置对比度为3(最大为3)
sensor.set_contrast(3)
# 设置自动增益的上限
sensor.set_gainceiling(64)
## 取消自动增益，设置固定增益
#sensor.set_auto_gain(False, gain_db=32)
sensor.skip_frames(time=2000)


# 创建串口通信对象
uart = UART(3, 115200, bits=8, parity=None, stop=1)
# 创建image对象
img = sensor.snapshot()
# clock
clock = time.clock()
# 创建检测区间
# 该框原点坐标
findLen = [120, 100]
subXY = [(img.width() // 2) - (findLen[0] // 2), (img.height() // 2) - (findLen[1] // 2)]
scope = [subXY[0], subXY[1], findLen[0], findLen[1]]


# 发送坐标数据
def UART_SendXY(recognize):
    global uart
    sendarray = str(recognize[0]) + ' ' + str(recognize[1])
    uart.write(sendarray)
    print(sendarray)
    print('')


while True:
    clock.tick()
    img = sensor.snapshot()
#    去畸变
    img.lens_corr(strength=1.8, zoom=1.0)
    img.draw_rectangle(scope, thickness=1)

    target = img.find_eye(scope)
    if target != (0, 0):
        img.draw_cross(target[0], target[1], thickness=1)
        UART_SendXY(target)
    print('fps:', end=' ')
    print(clock.fps())
